package com.cch.platform.util;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class JsonTreeUtil {
	
	public static Set<TreeNode> getTree(List<Object> datalst, String idname,
			String pidname, String sortname, String titlename) {

		if(datalst==null||datalst.size()==0){
			return null;
		}
		Map<String, TreeNode> nodes = new HashMap<String, JsonTreeUtil.TreeNode>();
		TreeNode root = new TreeNode();
		for (Object data : datalst) {
			TreeNode node=new TreeNode(data, idname,pidname, sortname, titlename);
			nodes.put(node.getId(),node );
		}
		for (TreeNode node : nodes.values()) {
			if (node.pid == null || "".equals(node.pid)) {
				root.addChild(node);
			} else {
				TreeNode tempnode = nodes.get(node.pid);
				if (tempnode != null) {
					tempnode.addChild(node);
				}
			}
		}
		return root.getChildren();
	}

	public static class TreeNode {
		String id;
		String pid;
		String text;
		int sort;
		Object attributes;
		Set<TreeNode> children = new TreeSet<TreeNode>(
				new Comparator<TreeNode>() {
					@Override
					public int compare(TreeNode o1, TreeNode o2) {
						if (o1.sort < o2.sort) {
							return -1;
						}
						return 1;
					}
				});

		public TreeNode() {
		}

		TreeNode(Object data, String idname, String pidname, String sortname,
				String titlename) {
			Map<Object, Object> dmap = MapUtil.bean2Map(data);
			id=(String)dmap.get(idname);
			pid=(String)dmap.get(pidname);
			text=(String)dmap.get(titlename);
			if(dmap.get(sortname)!=null&&dmap.get(sortname).toString()!=""){
				sort=(Integer) dmap.get(sortname);
			}else{
				sort=0;
			}
			attributes=data;
		}

		boolean addChild(TreeNode e) {
			return children.add(e);
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getText() {
			return text;
		}

		public void setText(String text) {
			this.text = text;
		}

		public Object getAttributes() {
			return attributes;
		}

		public void setAttributes(Object attributes) {
			this.attributes = attributes;
		}

		public Set<TreeNode> getChildren() {
			return children;
		}

		public void setChildren(Set<TreeNode> children) {
			this.children = children;
		}

	}
}
